﻿/*
 * Created by SharpDevelop.
 * User: Hellen(LongFan)
 * Date: 2015-11-23
 * Time: 18:40
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Windows.Forms;
using System.IO.Ports;			//串口
using System.Diagnostics;		//进程
using System.Reflection;		//程序名
using System.Runtime.InteropServices;	//DLLImport

namespace Comm
{
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		private const int WS_SHOWNORMAL = 1;
		[DllImport("User32.dll")]
		private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd); 
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{	
			Process instance = RunningInstance();
			if( instance == null )
			{//no the same application is running
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new MainForm());
			}
			else
			{
				ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
				SetForegroundWindow(instance.MainWindowHandle);
			}
		}
		
		private static Process RunningInstance()
		{
			//get current process filename and main path
			string CurrentProcessPthName = Process.GetCurrentProcess().MainModule.FileName;
			//get all "BHN Collection APP" process
			Process[] SameProcessArrary = Process.GetProcessesByName("BHN Collection APP");
			foreach(Process p in SameProcessArrary)
			{
				if(p.Id != Process.GetCurrentProcess().Id)
				{//if not the current process, check if the path is same
					//acque the process path
					string ExePath = p.MainModule.FileName;
					if( ExePath == CurrentProcessPthName )
					{//if it is the same .exe, return the current process
						return p ;
					}
				}
			}
			return null ;
		}
	}
}
